package org.mch.func.encode;

import java.awt.event.ActionEvent;
import java.io.ByteArrayInputStream;
import java.util.Properties;

import org.mch.biz.ui.FuncEvent;
import org.mch.biz.ui.FuncPanel;
import org.mch.comm.db.utils.SQLHelper;

/**
 * 描述：编码操作工具事件；
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class ClientEvent extends FuncEvent {
	private static final long serialVersionUID = 1L;

	private Native2ASCII na = new Native2ASCII();

	public ClientEvent(FuncPanel panel) {
		super(panel);
	}

	protected void onButtonClick(ActionEvent e) throws Exception {
		if (e.getSource() == getPanel().getButton_upper()) {
			toUpper();
		} else if (e.getSource() == getPanel().getButton_lower()) {
			toLower();
		} else if (e.getSource() == getPanel().getBtn_rep()) {
			toReplace();
		} else if (e.getSource() == getPanel().getBtn_sqlin()) {
			toSQLIN();
		} else if (e.getSource() == getPanel().getBtn_native2ascii()) {
			toNative2ASCII();
		} else if (e.getSource() == getPanel().getBtn_ascii2native()) {
			toASCII2Native();
		}
	}

	public void toASCII2Native() throws Exception {
		String textUp = getPanel().getTextArea_up().getText();
		if (textUp == null || textUp.trim().equals("")) {
			return;
		}

		getPanel().getTextArea_down().setText(this.na.ascii2native(textUp));
	}

	public void toNative2ASCII() throws Exception {
		String textUp = getPanel().getTextArea_up().getText();
		if (textUp == null || textUp.trim().equals("")) {
			return;
		}

		getPanel().getTextArea_down().setText(this.na.native2ascii(textUp));
	}

	public void toSQLIN() throws Exception {
		String textUp = getPanel().getTextArea_up().getText();
		if (textUp == null || textUp.trim().equals("")) {
			return;
		}
		String[] ss = textUp.split("\n");
		String sql = SQLHelper.getINSQL(getPanel().getText_infield().getText(), ss);

		getPanel().getTextArea_down().setText(sql);
	}

	public void toReplace() throws Exception {
		String textUp = getPanel().getTextArea_up().getText();
		if (textUp == null || textUp.trim().equals("")) {
			return;
		}
		ByteArrayInputStream upis = new ByteArrayInputStream(textUp.getBytes());
		Properties pro = new Properties();
		pro.load(upis);

		String textDown = getPanel().getTextArea_down().getText();

		String[] keys = pro.keySet().toArray(new String[0]);
		for (int i = 0; i < keys.length; i++) {
			textDown = textDown.replace(keys[i], pro.getProperty(keys[i]));
		}

		getPanel().getTextArea_down().setText(textDown);
	}

	public void toUpper() {
		String text = getPanel().getTextArea_up().getText();
		getPanel().getTextArea_down().setText(text.toUpperCase());
	}

	public void toLower() {
		String text = getPanel().getTextArea_up().getText();
		getPanel().getTextArea_down().setText(text.toLowerCase());
	}

	public EncodePanel getPanel() {
		return (EncodePanel) super.getPanel();
	}
}